package com.tdam2011.grupo05.database.dao;

import java.util.Date;
import java.util.List;
import java.util.Set;

import android.content.ContentResolver;
import android.content.ContentUris;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.net.Uri;
import android.provider.BaseColumns;

import com.google.common.collect.Lists;
import com.google.common.collect.Sets;
import com.tdam2011.grupo05.database.content.TdamContentProvider;
import com.tdam2011.grupo05.entities.contact.ContactWeb;
import com.tdam2011.grupo05.entities.message.MessageWeb;
import com.tdam2011.grupo05.entities.message.MessageWeb.Type;
import com.tdam2011.grupo05.entities.thread.ThreadWeb;
import com.tdam2011.grupo05.entities.thread.ThreadWeb.State;

public class ThreadWebDao implements Dao<ThreadWeb> {

	private static final String[] PROJECTION = { ThreadWeb.COL_ID,
			ThreadWeb.COL_ID_USER, ThreadWeb.COL_STATE,
			ThreadWeb.COL_TIMESTAMP, ThreadWeb.COL_NAME,
			ThreadWeb.COL_ID_ACCOUNT };

	private final ContentResolver cr;

	public ThreadWebDao(Context context) {
		cr = context.getContentResolver();
	}

	@Override
	public long save(ThreadWeb t) {
		final ContentValues cv = new ContentValues();
		cv.put(ThreadWeb.COL_ID_USER, t.getUser().getId());
		cv.put(ThreadWeb.COL_STATE, t.getState().name());
		cv.put(ThreadWeb.COL_NAME, t.getName());
		cv.put(ThreadWeb.COL_TIMESTAMP, t.getDate().getTime());
		cv.put(ThreadWeb.COL_ID_ACCOUNT, t.getIdAccount());
		Uri u = cr.insert(TdamContentProvider.THREAD_CONTENT_URI, cv);
		return ContentUris.parseId(u);
	}

	@Override
	public void update(ThreadWeb t) {
		final ContentValues cv = new ContentValues();
		cv.put(ThreadWeb.COL_ID, t.getId());
		cv.put(ThreadWeb.COL_ID_USER, t.getUser().getId());
		cv.put(ThreadWeb.COL_NAME, t.getName());
		cv.put(ThreadWeb.COL_STATE, t.getState().name());
		cv.put(ThreadWeb.COL_ID_ACCOUNT, t.getIdAccount());
		cv.put(ThreadWeb.COL_TIMESTAMP, t.getDate().getTime());
		cr.update(TdamContentProvider.THREAD_CONTENT_URI, cv, BaseColumns._ID
				+ "= ?", new String[] { String.valueOf(t.getId()) });
	}

	@Override
	public void delete(ThreadWeb t) {
		cr.delete(TdamContentProvider.THREAD_CONTENT_URI, BaseColumns._ID
				+ "=?", new String[] { String.valueOf(t.getId()) });
	}

	@Override
	public ThreadWeb get(long id) {
		ThreadWeb t = null;
		Cursor c = cr.query(TdamContentProvider.THREAD_CONTENT_URI, PROJECTION,
				BaseColumns._ID + "= ?", new String[] { String.valueOf(id) },
				"1");
		if (c.moveToFirst()) {
			t = buildThreadWeb(c);
		}
		if (!c.isClosed()) {
			c.close();
		}
		return t;
	}

	public ThreadWeb getByContact(long idContact) {
		ThreadWeb t = null;
		Cursor c = cr.query(TdamContentProvider.THREAD_CONTENT_URI, PROJECTION,
				ThreadWeb.COL_ID_USER + "= ?",
				new String[] { String.valueOf(idContact) }, "1");
		if (c.moveToFirst()) {
			t = buildThreadWeb(c);
		}
		if (!c.isClosed()) {
			c.close();
		}
		return t;
	}

	public ThreadWeb getThreadWebByName(String name) {
		ThreadWeb t = null;
		Cursor c = cr.query(TdamContentProvider.THREAD_CONTENT_URI, PROJECTION,
				ThreadWeb.COL_NAME + "= ?", new String[] { name }, "1");
		if (c.moveToFirst()) {
			t = buildThreadWeb(c);
		}
		if (!c.isClosed()) {
			c.close();
		}
		return t;
	}

	@Override
	public List<ThreadWeb> getAll() {
		List<ThreadWeb> mList = Lists.newArrayList();
		Cursor c = cr.query(TdamContentProvider.THREAD_CONTENT_URI, PROJECTION,
				null, null, "1");
		if (c.moveToFirst()) {
			do {
				mList.add(buildThreadWeb(c));
			} while (c.moveToNext());
		}
		if (!c.isClosed()) {
			c.close();
		}
		return mList;
	}

	@Override
	public Cursor getCursor(String selection, String[] selectionArgs,
			String sortOrder) {
		return cr.query(TdamContentProvider.THREAD_CONTENT_URI, PROJECTION,
				selection, selectionArgs, sortOrder);
	}

	public ThreadWeb buildThreadWeb(Cursor c) {
		if (c != null) {
			final ThreadWeb t = new ThreadWeb();
			t.setId(c.getLong(c.getColumnIndex(ThreadWeb.COL_ID)));
			t.setState(State.valueOf(c.getString(c
					.getColumnIndex(ThreadWeb.COL_STATE))));
			t.setDate(new Date(c.getLong(c
					.getColumnIndex(ThreadWeb.COL_TIMESTAMP))));
			t.setName(c.getString(c.getColumnIndex(ThreadWeb.COL_NAME)));
			t.setIdAccount(c.getLong(c.getColumnIndex(ThreadWeb.COL_ID_ACCOUNT)));

			long idUser = c.getLong(c.getColumnIndex(ThreadWeb.COL_ID_USER));
			Cursor u = cr.query(TdamContentProvider.USER_CONTENT_URI,
					new String[] { ContactWeb.COL_ID, ContactWeb.COL_ID_PHONE,
							ContactWeb.COL_ID_CONTACTO, ContactWeb.COL_NAME },
					BaseColumns._ID + "=?",
					new String[] { String.valueOf(idUser) }, "1");
			t.setUser(buildContactWeb(u));

			t.setMessages(buildMessages(t.getId()));

			return t;
		} else {
			return null;
		}

	}

	private Set<MessageWeb> buildMessages(long idThread) {
		Set<MessageWeb> mSet = Sets.newLinkedHashSet();
		Cursor c = cr.query(TdamContentProvider.MESSAGE_CONTENT_URI,
				new String[] { MessageWeb.COL_ID, MessageWeb.COL_ID_THREAD,
						MessageWeb.COL_RESULT, MessageWeb.COL_STATE,
						MessageWeb.COL_TEXT, MessageWeb.COL_TIMESTAMP,
						MessageWeb.COL_TYPE }, MessageWeb.COL_ID_THREAD + "=?",
				new String[] { String.valueOf(idThread) }, "1");
		if (c.moveToFirst()) {
			do {
				final MessageWeb m = buildMessageFromCursor(c);
				if (m != null) {
					mSet.add(m);
				}
			} while (c.moveToNext());
		}
		if (!c.isClosed()) {
			c.close();
		}
		return mSet;
	}

	private MessageWeb buildMessageFromCursor(Cursor c) {
		if (null != c) {
			MessageWeb m = new MessageWeb();
			m.setId(c.getLong(c.getColumnIndex(MessageWeb.COL_ID)));
			m.setIdThread(c.getLong(c.getColumnIndex(MessageWeb.COL_ID_THREAD)));
			m.setResult(c.getString(c.getColumnIndex(MessageWeb.COL_RESULT)));
			m.setState(com.tdam2011.grupo05.entities.message.MessageWeb.State.valueOf(c
					.getString(c.getColumnIndex(MessageWeb.COL_STATE))));
			m.setText(c.getString(c.getColumnIndex(MessageWeb.COL_TEXT)));
			m.setTimestamp(new Date(c.getLong(c
					.getColumnIndex(MessageWeb.COL_TIMESTAMP))));
			m.setType(Type.valueOf(c.getString(c
					.getColumnIndex(MessageWeb.COL_TYPE))));

			return m;

		} else {
			return null;
		}

	}

	private ContactWeb buildContactWeb(Cursor c) {
		if (c.moveToFirst()) {
			ContactWeb contact = new ContactWeb();
			contact.setId(c.getInt(c.getColumnIndex(ContactWeb.COL_ID)));
			contact.setIdPhone((int) c.getLong(c
					.getColumnIndex(ContactWeb.COL_ID_PHONE)));
			contact.setIdContacto((int) c.getLong(c
					.getColumnIndex(ContactWeb.COL_ID_CONTACTO)));
			contact.setName(c.getString(c.getColumnIndex(ContactWeb.COL_NAME)));
			if (!c.isClosed()) {
				c.close();
			}
			return contact;
		} else {
			return null;
		}
	}

}
